package com.ssm.property.server.controller.unit;

import com.github.pagehelper.PageInfo;
import com.jee.ssm.common.support.Const;
import com.jee.ssm.common.utils.UUIDFactory;
import com.jee.ssm.common.web.json.Tip;
import com.jee.ssm.common.web.param.ParamMap;
import com.ssm.property.dao.model.building.Building;
import com.ssm.property.dao.model.residence.Residence;
import com.ssm.property.dao.model.unit.Unit;
import com.ssm.property.rpc.api.building.BuildingService;
import com.ssm.property.rpc.api.residence.ResidenceService;
import com.ssm.property.rpc.api.room.RoomService;
import com.ssm.property.rpc.api.unit.UnitService;
import com.ssm.upms.dao.model.Account;
import com.ssm.upms.log.AdminControllerLog;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 单元管理 Controller
 * @author GaoXiang
 * @version 1.0
 */
@Controller
@RequestMapping("/unit")
public class UnitController  {



    /**
     * 进入单元添加页面 携带一个生成的id --> longId
     * @param model 返回的实体容器
     * @return 添加页面
     */
    @RequestMapping(value="/add")
    @RequiresPermissions("unit:add")
    public String add(HttpServletRequest request, ModelMap model){
        HttpSession session = request.getSession();
        Account account = (Account)session.getAttribute(Const.ACCOUNT);
        model.put("type",account.getType());
        if(account.getType()==21) {
            model.put("residence", residenceService.selectById(account.getInfoId().split(",")[1]));
        }
        model.put("longId", UUIDFactory.getStringId());
        return "manager/unit/add";
    }

    /**
     * 批量添加单元
     * @return 添加页面
     */
    @RequestMapping(value = "/adds")
    @RequiresPermissions("unit:add")
    public String adds(HttpServletRequest request, ModelMap model) {
        HttpSession session = request.getSession();
        Account account = (Account)session.getAttribute(Const.ACCOUNT);
        model.put("type",account.getType());
        if(account.getType()==21) {
            model.put("residence", residenceService.selectById(account.getInfoId().split(",")[1]));
        }
        return  "manager/unit/adds";
    }


    /**
     * 进入单元编辑页面
     * @param model 返回单元的容器
     * @param id 单元id
     * @return 编辑页面
     */
    @RequestMapping(value="/edit")
    @RequiresPermissions("unit:edit")
    public String edit(HttpServletRequest request, ModelMap model, @RequestParam String id) {
        HttpSession session = request.getSession();
        Account account = (Account)session.getAttribute(Const.ACCOUNT);
        model.put("type",account.getType());
       Unit unit= unitService.selectById(id);
       unit.setResidence(residenceService.selectById(unitService.selectById(id).getResidenceId()));
       unit.setBuilding(buildingService.selectById(unitService.selectById(id).getBuildingId()));
        model.put("data",unit);
        return "manager/unit/edit";
    }


    /**
     * 单元添加
     * @param unit 带id的单元对象
     * @return 成功状态
     */
    @RequestMapping(value="/save")
    @ResponseBody
    @RequiresPermissions("unit:add")
    @AdminControllerLog(description = "添加单元" )
    public Tip save(Unit unit,HttpServletRequest request)  {

        try {
            ParamMap paramMap=new ParamMap(request);
            paramMap.put("buildingId",unit.getBuildingId());
            paramMap.put("number",unit.getNumber());
            if(unitService.count(paramMap) >0){
                return  new Tip(1,"单元编号已存在");
            }
            unitService.insert(unit);
            return new Tip();
        } catch (Exception e) {
            //e.printStackTrace();
            return new Tip(1,"添加失败！");
        }

    }


    /**
     * 批量添加单元
     * @param unit 单元对象
     * @return 成功状态
     */
    @RequestMapping(value="/saves")
    @ResponseBody
    @AdminControllerLog(description = "添加单元" )
    public Tip saves(Unit unit,String count,HttpServletRequest request)  {
        try {
            int number=Integer.parseInt(unit.getNumber());
            int total=Integer.parseInt(count)+number;
            ParamMap paramMap=new ParamMap(request);
            for(int i=number;i<total;i++){
                paramMap.put("buildingId",unit.getBuildingId());
                paramMap.put("number",String.valueOf(i));
                if(unitService.count(paramMap) >0){i=i+1;}
                 unit.setId(UUIDFactory.getStringId());
                 unit.setNumber(String.valueOf(i));
                 unit.setResidenceId(unit.getResidenceId());
                 unit.setBuildingId(unit.getBuildingId());
                unitService.insert(unit);
            }
            return new Tip();
        } catch (Exception e) {
            //e.printStackTrace();
            return new Tip(1,"批量添加失败");
        }
    }


    /**
     * 根据 id 修改单元
     * @param unit 带id的单元对象
     * @return 成功状态
     */
    @RequestMapping(value="/update")
    @ResponseBody
    @RequiresPermissions("unit:edit")
    @AdminControllerLog(description = "修改单元" )
    public Tip update(Unit unit,HttpServletRequest request) {
        try {
            if (!unitService.selectById(request.getParameter("id")).getNumber().equals(unit.getNumber())){
                ParamMap paramMap=new ParamMap(request);
                paramMap.put("buildingId",unit.getBuildingId());
                paramMap.put("number",unit.getNumber());
                if(unitService.count(paramMap) >0){
                    return  new Tip(1,"单元编号已存在");
                }
            }
            unitService.updateById(unit);
            return new Tip();
        } catch (Exception e) {
            //e.printStackTrace();
            return new Tip(1,"修改失败！");
        }

    }


    /**
     * 根据 id 删除单元
     * @param id 单元id
     * @return 成功状态
     */
    @RequestMapping(value="/delete")
    @ResponseBody
    @RequiresPermissions("unit:delete")
    @AdminControllerLog(description = "删除单元" )
    public Tip delete(@RequestParam String id) {

        try {

            roomService.deleteByUnitId(id);//删房间
          /*  //查设备
            List<Equipment> equipmentList = equipmentService.selectByUnitId(id);
            if(equipmentList!=null && !equipmentList.isEmpty()){
                for (Equipment equipment:equipmentList) {
                    List<Card> cardList = cardService.selectByEquipmentId(equipment.getId());
                    if(cardList!=null && !cardList.isEmpty()){
                        for (Card card:cardList) {
                            cardService.deleteById(card.getId());//删卡
                        }
                    }
                }
            }
            if(equipmentList!=null && !equipmentList.isEmpty()){
                for (Equipment equipment:equipmentList) {
                    equipmentCardService.deleteByEquipmentId(equipment.getId());//根据设备id 删除设备与卡关联信息
                    equipmentService.selectById(equipment.getId());//删设备
                }
            }*/
         /*   unitService.deleteById(id);//删单元*/
          /*  userRoomService.deleteByUnitId(id);*/
            return new Tip();
        } catch (Exception e) {
            return new Tip(1,"删除失败！");
        }

    }


    /**
     * 根据 id 列表批量删除
     * @param ids 单元id List
     * @return 成功状态
     */
    @RequestMapping(value="/deleteByIds")
    @ResponseBody
    @RequiresPermissions("unit:delete")
    @AdminControllerLog(description = "批量删除单元" )
    public Tip deleteByIds(@RequestParam("ids") List<String> ids) {

        try {
            unitService.deleteByIds(ids);
            return new Tip();
        } catch (Exception e) {
            return new Tip(1,"批量删除失败！");
        }

    }


    /**
     * 根据 id 查找单元
     * @param id 单元id
     * @return 单元对象 json
     */
    @RequestMapping(value="/findJson")
    @ResponseBody
    @RequiresPermissions("unit:list")
    public Unit find(@RequestParam String id) {

        return unitService.selectById(id);
    }


    /**
     * 获取单元列表 获取全部 不分页
     * @param request 请求参数
     * @return 单元列表页面
     */
    @RequestMapping(value="/all")
    @RequiresPermissions("unit:list")
    public String all(HttpServletRequest request, ModelMap modelMap) {

        return list(request,modelMap,1,0);
    }


    /**
     * 获取单元列表 分页
     * @param request 请求参数
     * @param page 第几页
     * @param size 每页大小
     * @return 单元列表页面
     */
    @RequestMapping(value="/list")
    @RequiresPermissions("unit:list")
    public String list(HttpServletRequest request, ModelMap modelMap, Integer page, Integer size) {
        HttpSession session=request.getSession();
        Account account= (Account) session.getAttribute(Const.ACCOUNT);
        ParamMap paramMap=new ParamMap(request);
        if (account.getType()==2) {
            paramMap.put("estateId",account.getInfoId());
        }else if(account.getType()==21){
       /*     if(estateService.selectById(account.getInfoId().split(",")[0]) != null){
                paramMap.put("estateId",account.getInfoId().split(",")[0]);
            }*/
            String residenceId = account.getInfoId().split(",")[1];
            paramMap.put("residenceId",residenceId);
            //单元数量
            Long countUnit = buildingService.countUnit(paramMap);
            modelMap.put("countUnit",countUnit);
            //房间数量
            Long countRoom = buildingService.countRoom(paramMap);
            modelMap.put("countRoom",countRoom);
            //男性数量
            Long countMale = buildingService.countMale(paramMap);
            modelMap.put("countMale",countMale);
            //女性数量
            Long countFemale = buildingService.countFemale(paramMap);
            modelMap.put("countFemale",countFemale);
            //60以上
            Long countOld = buildingService.countOld(paramMap);
            modelMap.put("countOld",countOld);
            //16以下
            Long countChild = buildingService.countChild(paramMap);
            modelMap.put("countChild",countChild);
        }/*else if(account.getType()==5){
            List<PoliceResidence> policeResidenceList= policeResidenceService.findByPoliceId(account.getInfoId());
            List<String> policeIdList=new ArrayList<String>();
            if(policeResidenceList.size()>0){
                for(PoliceResidence pr:policeResidenceList){
                    policeIdList.add(pr.getResidenceId());
                }
            }else {
                policeIdList.add("0");
            }
            paramMap.put("policeIdList", policeIdList);
        }*/
        List<Residence> residences = residenceService.listWithoutPage(paramMap);//搜索下拉框选择小区
        PageInfo<Unit> pageInfo=unitService.list(paramMap,page,size);
        for (Unit unit:pageInfo.getList()){
            unit.setResidence(residenceService.selectById(unit.getResidenceId()));
            unit.setBuilding(buildingService.selectById(unit.getBuildingId()));
        }
        modelMap.put("residences",residences);//搜索下拉框选择小区
        modelMap.put("type",account.getType());
        modelMap.put("pageInfo",pageInfo);
        modelMap.putAll(paramMap);
        return "manager/unit/list";
    }



    /**
     * 单元数据导出
     * 2017-5-22 韩榕榕 单元导出
     * @param request 请求参数
     * @param response 响应参数
     * @throws IOException IO异常
     */
    @RequestMapping(value = "/exportEcxel")
    @RequiresPermissions("unit:exportEcxel")
    public void exportEcxel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ParamMap paramMap = new ParamMap(request);
        HttpSession session=request.getSession();
        Account account= (Account) session.getAttribute(Const.ACCOUNT);
        if(account.getType() == 2) {
            paramMap.put("estateId", account.getInfoId());
        }else if(account.getType()==21){
            paramMap.put("estateId",account.getInfoId().split(",")[0]);
            paramMap.put("residenceNum",account.getInfoId().split(",")[1]);
        }/*else if(account.getType()==5){
            List<PoliceResidence> policeResidenceList= policeResidenceService.findByPoliceId(account.getInfoId());
            List<String> policeIdList=new ArrayList<String>();
            if(policeResidenceList.size()>0){
                for(PoliceResidence pr:policeResidenceList){
                    policeIdList.add(pr.getResidenceId());
                }
            }else {
                policeIdList.add("0");
            }

            paramMap.put("policeIdList", policeIdList);
        }*/
       List<Unit> unitList=unitService.listWithoutPage(paramMap);
        String originFileUrl = request.getServletContext().getRealPath("/download/info.xlsx");
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), Unit.class, unitList);
        FileOutputStream fos = new FileOutputStream(originFileUrl);
        workbook.write(fos);
        String fileName = "单元导出.xls";
        fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        //设置文件MIME类型
        response.setContentType(request.getServletContext().getMimeType(fileName));
        //设置Content-Disposition
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        //读取文件
        InputStream in = new FileInputStream(originFileUrl);
        OutputStream out = response.getOutputStream();

        //写文件
        int b;
        while((b=in.read()) != -1) {
            out.write(b);
        }
        fos.close();
        in.close();
        out.close();
    }


    /**
     * 单元数据的导入
     * 2017-5-22 13:28:47 韩榕榕
     * @param session
     * @param file
     * @return 成功状态
     * @throws Exception
     */
    @RequestMapping(value = "/importExcel")
    @ResponseBody
    @RequiresPermissions("unit:importExcel")
    public Tip importExcel(HttpServletRequest request,HttpSession session, MultipartFile file) throws Exception {
        Tip tip = new Tip();
        Account account = (Account)session.getAttribute(Const.ACCOUNT);
            List<Unit> unitList= ExcelImportUtil.importExcel(file.getInputStream(),Unit.class,new ImportParams());
            Integer index = 0;
            ParamMap paramMap=new ParamMap(request);
            ParamMap p=new ParamMap(request);
            ParamMap para=new ParamMap(request);
            if(!unitList.isEmpty()) {
                for(Unit u : unitList) {
                    try {
                        if(account.getType()==1 || account.getType()==2){
                            paramMap.put("estateId",account.getInfoId());
                        }else if(account.getType()==21){
                            paramMap.put("residenceNum",account.getInfoId().split(",")[1]);
                        }
                        paramMap.put("code",u.getResidenceNumber());
                        Residence residence=residenceService.selectByresCode(paramMap);
                        if( residence !=null){
                            p.put("residenceId",residence.getId());
                            p.put("number",u.getBuildingNumber());
                            Building building=buildingService.selectBybuilNumber(p);
                            if( building !=null){
                                if(unitService.count(para) >0){
                                    tip.setSuccess(false);
                                    tip.setCode(1);
                                    tip.setData("单元编号已存在");
                                }else{
                                    u.setId(UUIDFactory.getStringId());
                                    u.setResidenceId(residence.getId());
                                    u.setBuildingId(building.getId());
                                    unitService.insert(u);
                                    tip.setSuccess(true);
                                    tip.setCode(0);
                                    tip.setData("查找到" + unitList.size() + "条数据，导入成功" + index + "条，导入失败" + (unitList.size()-index) + "条，导入完成");
                                }
                            }else{
                                tip.setSuccess(false);
                                tip.setCode(1);
                                tip.setData("楼栋编号数据导入异常");
                            }
                        }else{
                            tip.setSuccess(false);
                            tip.setCode(1);
                            tip.setData("小区编号数据导入异常");
                        }
                        index ++;
                    } catch(Exception e) {
                        e.printStackTrace();
                        continue;
                    }
                }
            } else {
                tip.setSuccess(false);
                tip.setCode(2);
                tip.setData("导入信息为空，请检查上传的excel");
            }
        return tip;
    }

    /**
     * 获取单元列表
     * @return 单元列表页面
     */
    @RequestMapping(value="/checklist")
    @RequiresPermissions("unit:list")
    public String checklist(ModelMap modelMap, @RequestParam String buildingId) {
        List<Unit> list=unitService.chooseList(buildingId);
         for (Unit unit:list){
            unit.setBuilding(buildingService.selectById(unit.getBuildingId()));
        }
        modelMap.put("list", list);
        return  "manager/unit/chooseUnit";
    }



    /**
     * 楼栋单元数量
     * @return
     */
    @RequestMapping(value = "/countUnit")
    @ResponseBody
    public Map<String, Object> countUnit(HttpServletRequest request) throws Exception {

        Map<String, Object> map = new HashMap<String, Object>();
        Unit unit = new Unit();

        HttpSession session = request.getSession();
        Account account = (Account) session.getAttribute(Const.ACCOUNT);
        if (account.getType() == 2) {
            unit.setIntro(account.getInfoId());//保存物业id
        }else if(account.getType() == 21){
            unit.setResidenceId(account.getInfoId().split(",")[1]);
        }else if(account.getType() == 5){
            unit.setNumber(account.getInfoId());
        }

        List<Unit> queryAllBuild = unitService.findAllBuild(unit);
        int length = queryAllBuild.size();
        String[] nameArray = new String[length];

     /*   List<Echat> list = new ArrayList<Echat>();
        for(int i = 0 ;i<nameArray.length; i++  ){
            nameArray [i] = queryAllBuild.get(i).getIntro();
        }
        for(Unit community : queryAllBuild){
            unit.setBuildingId(community.getBuildingId());
            Unit re = unitService.countNumber(unit);
            Echat count= new Echat();
            count.setValue(re.getIntro());//数量
            count.setName(community.getIntro());

            list.add(count);
               map.put("value",list);
        map.put("name",nameArray);
        }*/

        return map;
    }



/*
    */
/**
     * 获取单元下的住户
     * @param request 请求参数
     * @return 住户列表
     *//*

    @RequestMapping(value="/user")
    public String user(HttpServletRequest request, ModelMap modelMap) {

        ParamMap paramMap=new ParamMap(request);
        HttpSession session = request.getSession();
        Account account = (Account)session.getAttribute(Const.ACCOUNT);
        if (account.getType() == 5){
            List<PoliceResidence> policeResidenceList= policeResidenceService.findByPoliceId(account.getInfoId());
            List<String> policeIdList=new ArrayList<String>();
            if(policeResidenceList.size()>0){
                for(PoliceResidence pr:policeResidenceList){
                    policeIdList.add(pr.getResidenceId());
                }
            }else {
                policeIdList.add("0");
            }
            paramMap.put("policeIdList", policeIdList);
        }
        List<User> users = userService.selectByUnitId(paramMap);
        modelMap.put("users",users);
        modelMap.put("type",account.getType());
        modelMap.putAll(paramMap);
        return "manager/unit/user";
    }
*/




    //---------------------------- property -------------------------------

    @Resource
    private UnitService unitService;

    @Resource
    private ResidenceService residenceService;

    @Resource
    private BuildingService buildingService;

   /* @Resource
    private UserService userService;

    @Resource
    private PoliceResidenceService policeResidenceService;
*/
    @Resource
    private RoomService roomService;

  /*  @Resource
    private EquipmentService equipmentService;

    @Resource
    private CardService cardService;

    @Resource
    private EquipmentCardService equipmentCardService;

    @Resource
    private UserRoomService userRoomService;

    @Resource
    private EstateService estateService;*/

}
